package com.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.CategoryVo;
import com.app.vo.ElectronicVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@Controller
@RequestMapping("/api/elc")
public class ElectronicController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private ElectronicService electronicService;
    @Autowired
    private PersonService personService;
    @Autowired
    private CategoryPhoneService categoryPhoneService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DepartmentService departmentService;


    @GetMapping("/getDropList")//下拉框查询
    public Result<Object> getDropList(
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
//        String[] categoryArr = {"品牌","型号"};//categoryPhone表
//        String[] categoryArr1 = {"类型"};//category表
//        String[] categoryArr2 = {"人员"};//categoryPhone表
        CategoryVo vo = new CategoryVo();
//        Integer deviceType = 56;
        List<CategoryModel> phoneListByPid = categoryService.getCategoryByPid(26);
        vo.setTypeList(phoneListByPid);
        List<CategoryModel> categoryModelList = categoryService.getCategoryByPid(56);
        vo.setDeviceTypeList(categoryModelList);//设备类型
        List<CategoryPhoneModel> categoryPhoneModelList = categoryPhoneService.getPhoneListByPid(0);//品牌
        List<CategoryPhoneModel> list = new ArrayList<>();
        for (int i = 0; i < categoryPhoneModelList.size(); i++) {
            List<CategoryPhoneModel> phoneDeviceList = categoryPhoneService.getPhoneListByPid(categoryPhoneModelList.get(i).getId());
            list.addAll(phoneDeviceList);
        }
        vo.setDeviceList(list);
        vo.setBrandList(categoryPhoneModelList);
        List<Integer> idList = departmentService.getDepId(user.getDepartmentId());
        List<PersonModel> personList = personService.otherPersonList(idList);
        if (personList != null && personList.size() > 0) {
            vo.setPersonList(personList);
        }
        return Result.success(vo);
    }

    @GetMapping("/getElcList")//设备管理分页查询
    public Result getElcList(
            @RequestParam("page") Integer page,
            @RequestParam("limit") Integer limit,
            @RequestParam("name") String name,
            Integer sortType,
                    //            @RequestParam(required = false) Integer brand,
//            @RequestParam(required = false) Integer deviceType,
                    HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        List<Integer> idList = departmentService.getDepId(user.getDepartmentId());
        List<Integer> personIdLIst = new ArrayList<>();
        List<PersonModel> modelList = personService.otherPersonList(idList);
        for (PersonModel value : modelList) {
            personIdLIst.add(value.getId());
        }
        Page<ElectronicModel> elcModelPage = electronicService.getPageElcList(page, limit, name, personIdLIst,sortType);
        List<ElectronicModel> elcModelList = elcModelPage.getRecords();
        for (ElectronicModel electronicModel : elcModelList) {//查其他表
            PersonModel personModel = personService.selectPersonById(electronicModel.getPersonId());
            if (personModel == null) {
                return Result.error(500, "该设备信息不存在");
            }
            electronicModel.setPersonName(personModel.getName());//获取人员名字
            //判断品牌名称是否为空
            if (electronicModel.getBrand() != null) {
                CategoryPhoneModel categoryPhoneModel1 = categoryPhoneService.getCatPhoneByPidAndId(0, electronicModel.getBrand());
                //判断查出来的电子设备品牌是否为空
                if (categoryPhoneModel1 != null) {
                    electronicModel.setBrandText(categoryPhoneModel1.getName());//品牌名称
                }
                //判断电子设备id和型号名称是否为空
                if (categoryPhoneModel1 != null && electronicModel.getDevice() != null) {
                    CategoryPhoneModel categoryPhoneModel2 = categoryPhoneService.getCatPhoneByPidAndId(categoryPhoneModel1.getId(), electronicModel.getDevice());
                    //判断查出来电子设备型号是否为空
                    if (categoryPhoneModel2 != null) {
                        electronicModel.setDeviceText(categoryPhoneModel2.getName());//型号名称
                    }
                }
            }
            //判断设备类型名称是否为空
            if (electronicModel.getDeviceType() != null) {
                CategoryModel model = categoryService.getCategoryById(electronicModel.getDeviceType());//设备类型
                //判断设备类型是否为空
                if (model != null) {
                    electronicModel.setDeviceTypeText(model.getName());
                }
            }

        }
        int count = (int) elcModelPage.getTotal();
        ElectronicVo vo = new ElectronicVo();
        vo.setCount(count);
        vo.setList(elcModelList);
        return Result.success(vo);
    }

    @PostMapping("/insertElc")//    新增/修改设备管理
    public Result<Object> insertElc(
            @RequestBody JSONObject json,
            HttpServletRequest request) {
        Object brand = json.get("brand");
        Object device = json.get("device");
        if (brand instanceof String || device instanceof String) {
            CategoryPhoneModel model = new CategoryPhoneModel();
            if (json.get("brand") instanceof String) {
                String brandText = json.get("brand").toString();
                model.setId(0);
                model.setPid(0);
                model.setName(brandText);
                model.setStatus(1);
                model.setSort(0);
                model.setCreateTime(CommonHelp.getNowTimestamp());
                categoryPhoneService.insert(model);
                brand = model.getId();
            } else {
                brand = Integer.valueOf(json.get("brand").toString());
            }
            CategoryPhoneModel model2 = new CategoryPhoneModel();
            if (json.get("device") instanceof String) {
                String deviceText = json.get("device").toString();
                model2.setId(0);
                if (json.get("brand") instanceof String) {
                    model2.setPid(model.getId());
                } else {
                    CategoryModel model3 = categoryService.getCategoryById(Integer.valueOf(brand.toString()));
                    model2.setPid(model3.getId());
                }
                model2.setName(deviceText);
                model2.setStatus(1);
                model2.setSort(0);
                model2.setCreateTime(CommonHelp.getNowTimestamp());
                categoryPhoneService.insert(model2);
                device = model2.getId();
            } else {
                device = Integer.valueOf(json.get("device").toString());
            }
            Integer id = Integer.valueOf(json.get("id").toString());
            String name = json.get("name").toString();
            Integer personId = Integer.valueOf(json.get("personId").toString());
            Integer deviceType = Integer.valueOf(json.get("deviceType").toString());
            String serialization = json.get("serialization").toString();
            String macAddress = json.get("macAddress").toString();
            Integer number = Integer.valueOf(json.get("number").toString());

            String token = request.getHeader("authori-zation");
            if (token == null) {
                return Result.error(405, "token不存在");
            }
            String userId = TokenUtils.verify(token);
            AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
            if (user == null) {
                return Result.error(406, "用户不存在");
            }
            ElectronicModel elcModel = new ElectronicModel();
            elcModel.setName(name);
            elcModel.setDevice(Integer.valueOf(device.toString()));
            elcModel.setBrand(Integer.valueOf(brand.toString()));
            elcModel.setDeviceType(deviceType);
            elcModel.setPersonId(personId);
            elcModel.setSerialization(serialization);
            elcModel.setMacAddress(macAddress);
            elcModel.setNumber(number);
            try {
                if (id > 0) {
                    elcModel.setId(id);
                    elcModel.setUpdateTime(CommonHelp.getNowTimestamp());
                    electronicService.update(elcModel);
                } else {
                    elcModel.setCreateTime(CommonHelp.getNowTimestamp());
                    electronicService.insert(elcModel);
                }
            } catch (Exception e) {
                System.out.println(e);
            }
            return Result.success(null);
        }


        Integer id = Integer.valueOf(json.get("id").toString());
        String name = json.get("name").toString();
        Integer deviceType = Integer.valueOf(json.get("deviceType").toString());
        Integer personId = Integer.valueOf(json.get("personId").toString());
        Integer number = Integer.valueOf(json.get("number").toString());
        String serialization = json.get("serialization").toString();
        String otherSerialization = null;
        if (json.containsKey("otherSerialization") && json.get("otherSerialization") != null) {
            otherSerialization = json.get("otherSerialization").toString();
        }
        String macAddress = json.get("macAddress").toString();
        String bluetoothAddress = json.get("bluetoothAddress").toString();
        String activationTime = null;
        if (json.containsKey("activationTime") && json.get("activationTime") != null) {
            activationTime = json.get("activationTime").toString();
        }
        String downTime = null;
        if (json.containsKey("downTime") && json.get("downTime") != null) {
            downTime = json.get("downTime").toString();
        }
        String mobile = null;
        if (json.containsKey("mobile") && json.get("mobile") != null) {
            mobile = json.get("mobile").toString();
        }
        String otherMobile = null;
        if (json.containsKey("otherMobile") && json.get("otherMobile") != null) {
            otherMobile = json.get("otherMobile").toString();
        }
        String idCard = null;
        if (json.containsKey("idCard") && json.get("idCard") != null) {
            idCard = json.get("idCard").toString();
        }
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        ElectronicModel elcModel = new ElectronicModel();
        elcModel.setName(name);
        elcModel.setDevice(Integer.valueOf(device.toString()));
        elcModel.setBrand(Integer.valueOf(brand.toString()));
        elcModel.setDeviceType(deviceType);
        elcModel.setPersonId(personId);
        elcModel.setSerialization(serialization);
        elcModel.setMacAddress(macAddress);
        elcModel.setNumber(number);
        if (otherSerialization != null) {
            elcModel.setOtherSerialization(otherSerialization);
        }
        if (bluetoothAddress != null) {
            elcModel.setBluetoothAddress(bluetoothAddress);
        }
        if (activationTime != null) {
            elcModel.setActivationTime(activationTime);
        }
        if (downTime != null) {
            elcModel.setDownTime(downTime);
        }
        if (mobile != null) {
            elcModel.setMobile(mobile);
        }
        if (otherMobile != null) {
            elcModel.setOtherMobile(otherMobile);
        }
        elcModel.setIdCard(idCard);


        try {
            if (id > 0) {
                elcModel.setId(id);
                elcModel.setUpdateTime(CommonHelp.getNowTimestamp());
                electronicService.update(elcModel);
            } else {
                elcModel.setCreateTime(CommonHelp.getNowTimestamp());
                electronicService.insert(elcModel);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return Result.success(null);
    }

    @GetMapping("/deleteById")//删除设备
    public Result<Object> deleteById(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        ElectronicModel roleModel = electronicService.getElcById(id);
        if (roleModel == null) {
            return Result.error(500, "该角色不存在");
        } else {
            electronicService.delete(id);
            return Result.success(null);
        }
    }

    //批量删除设备
    @DeleteMapping("/deleteElectronicBatchByIds")
    public Result<Object> deleteElectronicBatchByIds(@RequestParam("ids") String ids, HttpServletRequest request) {
        // 校验token并获取用户信息
        AdminUserModel user = validateTokenAndGetUser(request);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        return electronicService.deleteElectronicBatchByIds(ids);
    }

    // 校验token并获取用户信息的方法
    private AdminUserModel validateTokenAndGetUser(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            throw new IllegalArgumentException("token不存在");
        }
        String userId = TokenUtils.verify(token);
        return adminUserService.getUserByUserId(Integer.parseInt(userId));
    }
}
